package com.rdxy.sys.service.impl;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.rdxy.common.utils.FaceUtil;
import com.rdxy.common.utils.JwtUtil;
import com.rdxy.sys.entity.Menu;
import com.rdxy.sys.entity.User;
import com.rdxy.sys.entity.UserRole;
import com.rdxy.sys.mapper.UserMapper;
import com.rdxy.sys.mapper.UserRoleMapper;
import com.rdxy.sys.service.IMenuService;
import com.rdxy.sys.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 人道逍遥
 * @since 2023-05-18
 */
@Service
@Transactional
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private JwtUtil jwtUtil;

    @Resource
    private UserRoleMapper userRoleMapper;

    @Autowired
    private IMenuService menuService;

    @Override
    public Map<String, Object> login(User user) {

        LambdaQueryWrapper<User> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername,user.getUsername());

        User loginUser = this.baseMapper.selectOne(wrapper);
        if(loginUser!=null&&passwordEncoder.matches(user.getPassword(), loginUser.getPassword())){
            //String key ="user:"+UUID.randomUUID();

            //存入Redis
            loginUser.setPassword(null);
            //redisTemplate.opsForValue().set(key,loginUser,30, TimeUnit.MINUTES);

            String token = jwtUtil.createToken(loginUser);



            Map<String,Object> data=new HashMap<>();
            //data.put("token",key);
            data.put("token",token);
            return data;

        }

        return null;
    }

//    @Override
//    public Map<String, Object> login(User user) {
//        //根据用户名和密码查询
//        LambdaQueryWrapper<User> wrapper=new LambdaQueryWrapper<>();
//        wrapper.eq(User::getUsername,user.getUsername());
//        wrapper.eq(User::getPassword,user.getPassword());
//
//        User loginUser = this.baseMapper.selectOne(wrapper);
//        if(loginUser!=null){
//            String key ="user:"+UUID.randomUUID();
//
//            //存入Redis
//            loginUser.setPassword(null);
//            redisTemplate.opsForValue().set(key,loginUser,30, TimeUnit.MINUTES);
//
//            Map<String,Object> data=new HashMap<>();
//            data.put("token",key);
//            return data;
//
//        }
//
//        return null;
//    }

    @Override
    public Map<String, Object> getUserInfo(String token) {
        //根据token从Redis获取用户信息
        //Object obj = redisTemplate.opsForValue().get(token);

        User loginUser=null;
        try {
            loginUser = jwtUtil.parseToken(token, User.class);
        } catch (Exception e) {
            e.printStackTrace();
        }


        if(loginUser!=null){
            //User loginUser=JSON.parseObject(JSON.toJSONString(obj),User.class);
            Map<String,Object> data=new HashMap<>();
            data.put("name",loginUser.getUsername());
            data.put("avatar",loginUser.getAvatar());

            // 角色
            List<String> roleList = this.baseMapper.getRoleNameByUserId(loginUser.getId());
            data.put("roles",roleList);

            // 权限列表
            List<Menu> menuList = menuService.getMenuListByUserId(loginUser.getId());

            data.put("menuList",menuList);

            return data;

        }

        return null;
    }

    @Override
    public void logout(String token) {
        // redisTemplate.delete(token);
    }

    @Override
    public void addUser(User user) {
        // 写入用户表
        this.baseMapper.insert(user);

        // 写入用户角色表
        List<Integer> roleIdList = user.getRoleIdList();
        if(roleIdList!=null){
            for (Integer roleId : roleIdList) {
                userRoleMapper.insert(new UserRole(null,user.getId(),roleId));
            }
        }
    }

    @Override
    public User getUserById(Integer id) {
        User user = this.baseMapper.selectById(id);

        LambdaQueryWrapper<UserRole> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(UserRole::getUserId,id);

        List<UserRole> userRoleList = userRoleMapper.selectList(wrapper);


        List<Integer> roleIdList = userRoleList.stream()
                .map(userRole -> {
                    return userRole.getRoleId();
                })
                .collect(Collectors.toList());

        user.setRoleIdList(roleIdList);
        return user;
    }

    @Override
    public void updateUser(User user) {
        // 更新用户表
        this.baseMapper.updateById(user);

        //  删除原有角色
        LambdaQueryWrapper<UserRole> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(UserRole::getUserId,user.getId());
        userRoleMapper.delete(wrapper);

        // 设置角色
        List<Integer> roleIdList = user.getRoleIdList();
        if(roleIdList!=null){
            for (Integer roleId : roleIdList) {
                userRoleMapper.insert(new UserRole(null,user.getId(),roleId));

            }
        }
    }

    @Override
    public void deleteUserById(Integer id) {
        this.baseMapper.deleteById(id);

        LambdaQueryWrapper<UserRole> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(UserRole::getUserId,id);

        userRoleMapper.delete(wrapper);

    }

    @Override
    public Map<String, Object> faceLogin(String imageBase) {


        System.out.println(imageBase.length());
//        imageBase= JSONUtil.parseObj(imageBase).getStr("imageBase");
        try {

            List<User> users = this.baseMapper.selectList(null);
            for (User loginUser : users) {
                String face = FaceUtil.face(imageBase,loginUser.getImagebase());
                JSONObject str = JSON.parseObject(face);
                Object confidence = str.get("confidence");
                System.out.println(confidence);

                if(confidence!=null&&Double.parseDouble(confidence.toString())>80){
                    System.out.println(loginUser);
                    loginUser.setPassword(null);
                    //redisTemplate.opsForValue().set(key,loginUser,30, TimeUnit.MINUTES);

                    String token = jwtUtil.createToken(loginUser);



                    Map<String,Object> data=new HashMap<>();
                    //data.put("token",key);
                    data.put("token",token);
                    return data;

                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }


        return null;
    }

    @Override
    public boolean addFace(String imageBase,String token) {
        String detect= null;
        try {
            detect = FaceUtil.detect(imageBase);
        } catch (IOException e) {
            e.printStackTrace();
        }
        JSONObject a = JSON.parseObject(detect);
        String face_token = (String) a.getJSONArray("faces").getJSONObject(0).get("face_token");

        if(face_token!=null){
            try {
                String s = FaceUtil.addFace(face_token);
                System.out.println(s);
                Object face_added = JSON.parseObject(s).get("face_added");
                if(face_added!=null&&Integer.parseInt(String.valueOf(face_added))>0){
                    User user = jwtUtil.parseToken(token, User.class);
                    boolean rl = FaceUtil.removeFace(user.getImagebase());
                    if(rl){
                        user.setImagebase(face_token);
                        this.baseMapper.updateById(user);
                        return true;
                    }

                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return false;
    }


}
